import datetime
import functools
import logging

from absl import app

from coin.exchange.upbit_v1.kr_rest.product import UpbitProduct
from coin.exchange.okex.kr_rest.product import OkexProduct
import experimental.prophet as prophet


def model(coins):
  ts = prophet.global_timestamp()
  timer_1s = prophet.timer('1s')

  books_1 = []
  books_2 = []
  for coin in coins:
    product_1 = UpbitProduct.FromStr('%s-KRW' % coin)
    feed_1 = prophet.fastfeed_coin(product_1, 'Spot.Upbit')
    books_1 += [prophet.book(feed_1)]

    product_2 = OkexProduct.FromStr('%s-USDT' % coin)
    feed_2 = prophet.fastfeed_coin(product_2, 'Spot.Okex.v3')
    books_2 += [prophet.book(feed_2)]

  usdkrw_rate = 1200.
  premiums = []
  for coin, book_1, book_2 in zip(coins, books_1, books_2):
    mid_p_1 = (book_1.ask0.price + book_1.bid0.price) / 2. / usdkrw_rate
    mid_p_2 = (book_2.ask0.price + book_2.bid0.price) / 2.
    premiums += [(mid_p_1 / mid_p_2).named_ref('premium_%s' % coin)]

  min_premium = prophet.min(*premiums).named_ref('min_premium')
  max_premium = prophet.max(*premiums).named_ref('max_premium')
  premium_diff = (max_premium - min_premium).named_ref('premium_diff')

  counter = prophet.shared(int, 0).named_ref('counter')

  with prophet.control_if(ts % 10**9 == 0):
    prophet.printer('%t count=%s premium_diff=%sbp --- BTC:%s ETH:%s XRP:%s BCH:%s LTC:%s EOS:%s',
                    ts,
                    counter,
                    premium_diff * 10000.,
                    *premiums)
    aggregator = prophet.scalar_value_aggregator(
        [ts, counter, premium_diff, min_premium, max_premium, *premiums])

  prophet.assign(counter, counter + 1)

  return aggregator


def main(argv):
  coins = ['BTC', 'ETH', 'XRP', 'BCHABC', 'LTC', 'EOS']
  df = prophet.run_from_fastfeed_multiprocess(functools.partial(model, coins),
                                              datetime.date(2019, 8, 1),
                                              datetime.datetime(2019, 8, 1, 2),
                                              machine='feed-01.ap-northeast-1.aws')

  print(df)


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG')
  app.run(main)
